<?php
namespace app\admin\controller;
use app\admin\model\Cate as CateModel;
use app\admin\controller\Base;//权限验证
use think\Loader;
use think\Session;
class Cate extends Base{	
    public function index(){
		$model= new CateModel();
		//栏目分页
		$list = CateModel::paginate(10);
		$this->assign('list',$list);
		return $this->fetch('list');
	}
	
	public function add(){
		//栏目添加
		if(request()->isPost()){
			$data = [
				'catename' => input('catename'),
				'pic' => input('pic'),
				'title'=>input('title'),
				'cdesc'=>input('cdesc'),
				'addtime'=>date("Y-m-d H:i:s"),
			];
			if(input('state')=='on'){
                $data['state']=1;
            }
			if($_FILES['pic']['tmp_name']){
                $file = request()->file('pic');
                $info = $file->move(ROOT_PATH . 'public' . DS . 'static/uploads');
                $data['pic']='/uploads/'.$info->getSaveName();
			}
			$validate = Loader::validate('Cate');
			if(!$validate->check($data)){
				//场景验证
			   $this->error($validate->getError()); 
			   die();
			}
			
			if(db('cate')->insert($data)){
				return $this->success('添加栏目成功！','index');
			}else{
				return $this->error('添加栏目失败！');
			}
			return;
		}
		return $this->fetch('add');
	}
	
	public function edit(){
		//栏目名称修改
		$id=input('id');
		$cates=db('cate')->find($id);
		if(request()->isPost()){
			$data=[
				'id'=>input('id'),
				'catename'=>input('catename'),
				'pic' => input('pic'),
				'title'=>input('title'),
				'cdesc'=>input('cdesc'),
				'addtime'=>date("Y-m-d H:i:s"),
			];
			if(input('state')=='on'){
                $data['state']=1;
            }
			if($_FILES['pic']['tmp_name']){
                $file = request()->file('pic');
                $info = $file->move(ROOT_PATH . 'public' . DS . 'static/uploads');
                $data['pic']='/uploads/'.$info->getSaveName();
			}
			$validate = Loader::validate('Cate');//验证器
			if(!$validate->check($data)){
			   $this->error($validate->getError()); 
			   die();
			}
	        $save=db('cate')->update($data);
			if($save !== false){
				$this->success('修改栏目名称成功！','index');
			}else{
				$this->error('修改栏目名称失败！');
			}
			return;
		}
		$this->assign('cates',$cates);
		return $this->fetch('edit');
	}
	
	
	public function del(){
		//栏目删除
		$id=input('id');
		
		if(db('cate')->delete(input('id'))){
			$this->success('栏目删除成功！','index');
		}else{
			$this->error('栏目删除失败！');
		}

	}
	
	
}
